package com.shundr.auth.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.shundr.auth.channel.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.view.DialogAuth;
import com.shundr.auth.frame.constant.LContext;
import com.shundr.auth.frame.http.LHttpRequest;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.http.UserRequest;
import com.shundr.auth.user.model.UserInfo;

public class LoginActivity extends BaseActivity {
	private EditText etName;
	private EditText etPw;

	private ImageView iv_login;

	private Button btnLogin;
	private Button btnRegister;

	private Intent intent;

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UserRequest.LOGIN_SUCCESSED:
				final UserInfo user = (UserInfo) msg.obj;
				if (user != null) {
					LContext.setACCESS_TOKEN(user.getAccessToken());
					LContext.userInfo = user;
					DialogAuth dialogAuth = new DialogAuth(mContext, user);
					dialogAuth.show();
				}
				break;
			case LHttpRequest.REQUEST_FAILED:
				ToastHelper.toastShort(mContext, msg.obj.toString());
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);
		etName = (EditText) findViewById(R.id.et_name);
		etPw = (EditText) findViewById(R.id.et_pw);
		iv_login = (ImageView) findViewById(R.id.iv_login);
		iv_login.setImageResource(R.drawable.iv_user_login);

		btnLogin = (Button) findViewById(R.id.btn_login);
		btnRegister = (Button) findViewById(R.id.btn_register);

		btnLogin.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (check())
					new UserRequest(mContext, mHandler).login(etName.getText()
							.toString(), etPw.getText().toString());
			}
		});

		btnRegister.setVisibility(View.GONE);
		btnRegister.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(mContext, RegisterActivity.class));
			}
		});

		intent = getIntent();
		String phone = "";
		if (intent != null) {
			phone = intent.getStringExtra("phone");
			etName.setText(phone);
		}
	}

	private boolean check() {
		if (StringUtil.isNull(etName.getText().toString())) {
			ToastHelper.toastShort(mContext, "请输入手机号");
			return false;
		}
		if (StringUtil.isNull(etPw.getText().toString())) {
			ToastHelper.toastShort(mContext, "请输入密码");
			return false;
		}
		return true;
	}

	@Override
	public void onBackPressed() {
		if (intent != null) {
			setResult(500);
		}
		super.onBackPressed();
	}
}
